package jp.co.coretechno;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class AppMain extends Applet implements Runnable {
	private int width;
	private int height;
	private Thread th = null;
	private Image img;
	private Graphics bg;
	private Field field;
	private int frameCount = 0;
	
	public void init() {
		width = getSize().width;
		height = getSize().height;
		
		img = createImage(width, height);
		bg = img.getGraphics();
		
		field = new Field();
		
		addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				int code = e.getKeyCode();
								
				switch (code) {
				case KeyEvent.VK_LEFT:
					field.moveLeft();
					break;
				case KeyEvent.VK_RIGHT:
					field.moveRight();
					break;
				case KeyEvent.VK_DOWN:
					field.moveDown();
					break;
				case KeyEvent.VK_UP:
					if (field.canRotateBlockLeft()) {
						field.rotateBlockLeft();
					}
					break;
				case KeyEvent.VK_Z:
					if (field.canRotateBlockLeft()) {
						field.rotateBlockLeft();
					}
					break;
				case KeyEvent.VK_X:
					if (field.canRotateBlockRight()) {
						field.rorateBlockRight();
					}
					break;
				}
			}
		});
	}
	
	public void start() {
		if (th == null) {
			th = new Thread(this);
			th.start();
		}
	}
	
	public void stop() {
		th = null;
	}
	
	public void paint(Graphics g) {
		bg.clearRect(0, 0, width, height);
		field.drawField(bg);
    }
    
    public void update(Graphics g) {
    	
    	frameCount++;
    	if (frameCount % 10 == 0) {
    		field.moveDown();
    	}

    	paint(g);
    	g.drawImage(img, 0, 0, width, height, this);
    }
    
    public void run() {
    	Thread thisThread = Thread.currentThread();
    	
    	while (th == thisThread) {
    		try {
    			Thread.sleep(20);
    			repaint();
    		} catch (InterruptedException e) {
    		}
    	}
    }
}
